package com.Cfeng.XiaohuanChat.session;

import com.Cfeng.XiaohuanChat.domain.Resp;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.RequiredArgsConstructor;
import org.springframework.security.web.session.InvalidSessionStrategy;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @author Cfeng
 * @date 2022/8/21
 */

@RequiredArgsConstructor
public class SessionInvalidStrategy implements InvalidSessionStrategy {

    private final ObjectMapper objectMapper;
    //监听用户的登录状态过期， 过期后的处理
    @Override
    public void onInvalidSessionDetected(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        response.setContentType("application/json;charset=utf-8");
        PrintWriter writer = response.getWriter();
        writer.write(objectMapper.writeValueAsString(Resp.failed("登录状态过期，请返回重新登录")));
        writer.flush();
        writer.close();
    }
}
